$(function() {

    var shop_id = product.shop_id;

    $.each(categories,function(index,value){

      let parentSelected = '';

      if(product.category.parent.id == value.id){

        parentSelected = 'selected';

        let children = value.children;

        $.each(children,function(index,child){

          let childSelected = '';

          if(product.category.id == child.id)
            childSelected = 'selected';

          $(".child").append("<option value="+child.id+" "+childSelected+">"+child.name+"</option>");
        });
      }

      $(".parent").append("<option value="+value.id+" "+parentSelected+">"+value.name+"</option>");
    });

    

    $('.parent').on('change', function() {
      let that = $(this);
      let pid = that.val();
      $.each(categories,function(index,value){
        if( value.id == pid){
          let children = value.children;
          $(".child").empty()
          $.each(children,function(index,child){

            let selected = '';

            if(product.category.id == child.id)
              selected = 'selected';

            $(".child").append("<option value="+child.id+" "+selected+">"+child.name+"</option>");
          });
        }  　　　
      });
    });


    $('.child').on('change', function() {
      var that = $(this);
      var category_id = that.val();
    });


    $("#product-update").validate({
        ignore: ".uploader-input",
        rules: {
            name: {required: true},
            title: {required: true},
            parent_category: {required: true},
            child_category: {required: true},
            shop: {required: true},
            original: {required: true,number:true},
            price: {required: true,number:true},
            settlement: {required: true,number:true},
            stock: {required: true,digits:true},
            effect: {required: true},

            //cover_pic:{required: true},
            //share_pic:{accept:"JPEG|PNG"},
        },

        onfocusout: false,
        onkeyup: false,

        showErrors: function (errorMap, errorList) {
            $.each(errorList, function (i, v) {
                layer.tips(v.message, v.element, {tips: [3,'#000000'], time: 2000});
                return false;
            });
        },

        submitHandler: function (form) {

            let ele = document.getElementById("product-update");

            let formData = new FormData(ele);

            let files = $(".uploader-input");

            for (let i = 0; i < files.length; i++){
              formData.append("files[]", files[i]);
            }
            if( shop_id == null || shop_id ==""){
              layer.alert('请选择门店');
              return false;
            }
            formData.append("shop_id", shop_id);

            $.ajaxSetup({
              headers: {
                'X-CSRF-TOKEN': $("input[name='_token']").attr('value')
              }
            });

            $.ajax({
                type: 'POST',
                url: '/merchant/product/'+product.id,
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success : function(rersult) {
                    layer.msg(rersult.message, {time:2000, shift: -1}, function () {
                        if (rersult.status === true && rersult.url != null) {
                            $(window).attr('location', rersult.url);
                        }
                    });
                },
                error : function(e){
                    layer.msg(e.responseJSON.message);
                }
            });
        }


    });


    var uploadFileList = [];
    var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
    var maxSize = 1024 * 1024*10;
    var maxWidth = 600;
    var formData = new FormData();
    $(".uploader-input").on("change", function (e) {
        var that = $(this);
        var files = e.target.files[0];
        var reader = new FileReader();

        reader.readAsDataURL(files);

        reader.onload = function (e) {
          that.next().attr('src', e.target.result);
        };
    });


    $('#date_range').daterangepicker({
      autoApply: true,
      //showDropdowns: true,
      ranges: {
        '上周': [moment().subtract(6, 'days'), moment()],
        '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
        '本月': [moment().startOf('month'), moment().endOf('month')],
        '上年度': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')],
        '本年度': [moment().startOf('year'), moment().endOf('year')]
      },
      opens: 'left',
      showWeekNumbers: true,
      locale: {
        format: 'YYYY-MM-DD',
        separator: " - ",
        applyLabel: '确定',
        cancelLabel: '取消',
        customRangeLabel: '自定义',
        firstDay: 1
      },
      startDate: moment(product.date_begin),
      endDate: moment(product.date_end),
    }, function(start, end, label) {
        $('input[name="date_begin"]').attr('value',start.format('YYYY-MM-DD'));
        $('input[name="date_end"]').attr('value',end.format('YYYY-MM-DD'));
         //timeRangeChange = [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')];
         //console.log(timeRangeChange);
    });

    var checker = null;

    $("input:checkbox[name='effect']").on('click', function (e) {
        var that = $(this);
        var target = that.data('target');
        $("input:checkbox[name='effect']").not(this).attr("checked", false);

        if( $("input:checkbox[name='effect']").is(':checked') ) {
          $(".effect").hide();
          $("."+target).show();
        }
        else{
          $(".effect").hide();
        }
    });



    $("input[name='shop']").autocomplete({
      source : function(request, response) {
        $.get('/util/shops', {
            'term':request.term,
          }, function(data) {
            response($.map(data,function(item) {
              return {
                label: item.id+' - '+item.name,
                id:item.id
              }
            }));

          },'json');
        },

      select:function(e, ui) {
        shop_id = ui.item.id;
      },
      minLength: 2,
    });


    /**
     * Autocomplete the staff's infomation
     */
    $("input[name='staff']").autocomplete({
      source : function(request, response) {
        $.get('/util/charge', {
            'term':request.term,
          }, function(data) {
            response($.map(data,function(item) {
              return {
                label: item.name+' - '+item.username,
                label: item.name+' - '+item.username,
                id:item.id
              }
            }));

          },'json');
        },

      select:function(e, ui) {
        staff = ui.item.id;
      },
      minLength: 2,
    });


    /**
     * Cancel button event
     */
    $('.cancel').on('click', function() {
      parent.layer.closeAll();
    });


});